package br.edu.fasete.javaroad.plugin.gui.tablemodel;

import java.util.Vector;

import javax.swing.table.DefaultTableModel;

import br.edu.fasete.javaroad.model.ClassDescriptor;
import br.edu.fasete.javaroad.model.EntityList;
import br.edu.fasete.javaroad.model.InterfaceDescriptor;

public class ClassTableModel extends DefaultTableModel {
	private static String[] colunas = {"Entity", "Type",  "Persistent", "DAO"};
	private Class[] classes = {String.class, String.class, Boolean.class, Boolean.class};
	
	public ClassTableModel() {
		super(colunas, 0);
	}
	
	public String getColumnName(int arg0) {
		return colunas[arg0];
	}

	public Class getColumnClass(int arg0) {
		return classes[arg0];
	}
	
	public void adicionarClasse(String nome, boolean persistent, boolean dao) {
		Vector linha = new Vector();
		linha.add(nome);
		if(persistent)
			linha.add("Class");
		else
			linha.add("Interface");
		linha.add(new Boolean(persistent));
		linha.add(new Boolean(dao));
		super.addRow(linha);
	}
	
	public boolean isCellEditable(int rowIndex, int columnIndex) {  
		String tp = (String) getValueAt(rowIndex, 1);
		return ((tp.equalsIgnoreCase("class") && columnIndex >= 2) || columnIndex == 3);
	}  
	
	public void limparTabela() {
		while(this.getRowCount() > 0) {
			this.removeRow(0);
		}
	}
	
	public void persistirTodos() {
		setAll(new Boolean(true), 1);
	}
	
	public void persistirNenhum() {
		setAll(new Boolean(false), 1);
	}	
	
	public void crudTodos () {
		setAll(new Boolean(true), 2);
		
	}
	
	public void crudNenhum () {
		setAll(new Boolean(false), 2);
	}
	
	private void setAll(Object value, int column) {
		int linhas = this.getRowCount();
		for(int i = 0; i < linhas; i++) {
			setValueAt(value, i, column);
		}			
	}
	
	public EntityList getListClass() {
		EntityList listaClasses = new EntityList();
		int linhas = this.getRowCount();
		for(int i = 0; i < linhas; i++) {
			boolean persiste = ((Boolean) getValueAt(i, 2)).booleanValue();
			boolean dao = ((Boolean) getValueAt(i, 3)).booleanValue();
			if(((String)getValueAt(i,1)).equalsIgnoreCase("class") )
				listaClasses.addClass(new ClassDescriptor((String)getValueAt(i, 0), dao, persiste));
			else
				listaClasses.addClass(new InterfaceDescriptor((String)getValueAt(i, 0), dao));
		}		
		return listaClasses;	
	}
	
	public boolean testar() {
		boolean teste = true;
		int linhas = this.getRowCount();
		for(int i = 0; i < linhas; i++) {
			boolean persiste = ((Boolean) getValueAt(i, 2)).booleanValue();
			boolean crud = ((Boolean) getValueAt(i, 3)).booleanValue();
			if(crud && !persiste) {
				teste = false;
				break;
			}
		}			
		return teste;
		
	}
}
